package kr.ac.kaist.pointdaproject;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.ImageView;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.oned.Code39Writer;

public class CardBarcodeView extends ImageView {
	private static final String TAG = "CardBarcodeView";
	
	private static final int BARCODE_WIDTH = 700;
	private static final int BARCODE_HEIGHT	= 200;
	
	private String mCardNumber;
	private BarcodeFormat mFormat;

    public CardBarcodeView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

	public void setCardNumber(String cardnumber) {
		mCardNumber = cardnumber;
	}
	
	public void setCardBarcodeFormat(BarcodeFormat format) {
		mFormat = format;
	}
	
	public void create() {
		if(mCardNumber == null || mCardNumber.length() == 0) {
			Log.d(TAG, "card number is null or the length of card number is zero.");
			return;
		}
		
		int width = BARCODE_WIDTH/*getWidth()*/;
		int height = BARCODE_HEIGHT/*getHeight()*/;	
		
		BitMatrix matrix;

		CardBarcodeMultiFormatWriter writer = new CardBarcodeMultiFormatWriter();
		try {
			matrix = writer.encode(mCardNumber, mFormat, width, height);		 
			Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
			for (int x = 0; x < width; x++) {
				for (int y = 0; y < height; y++) {
					//bitmap.setPixel(x, y, matrix.get(x, y) ? Color.BLACK : Color.WHITE);
					if(matrix.get(x, y)) {
						bitmap.setPixel(x, y, Color.BLACK);
					}
			    }
			}			
			setImageBitmap(bitmap);
		}
		catch (com.google.zxing.WriterException e) {
			Log.e(TAG, "Failed to encode the barcode.");
		}
	}
}